package com.auto.printer.handler;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.auto.printer.common.exception.MyException;
import com.auto.printer.entity.dto.PdfConvertDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;

/**
 * @author LoveHuaHua
 * @date 2023年08月01日 8:28
 * @description believe in yourself
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Lazy))
public class PdfConvertManage {

    private final List<IPdfConvert> converters;

    public PdfConvertDTO convert(String fileUrl) throws Exception {
        byte[] bytes = HttpUtil.downloadBytes(fileUrl);
       return convert(fileUrl,bytes);
    }

    public PdfConvertDTO convert(String fileUrl,byte[] bytes) throws Exception {
        //文件转换
        PdfConvertDTO convert = converters.stream().filter(iPdfConvert -> iPdfConvert.isSupport(FileUtil.getSuffix(fileUrl))).max(Comparator.comparing(IPdfConvert::sort)).orElseThrow(() -> new MyException("文件后缀名不支持!")).convert(fileUrl, bytes);
        return convert;
    }
}
